import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/empty.dart';
import 'package:wallpaper/components/images/image_load.dart';
import 'package:wallpaper/components/images/image_view.dart';
import 'package:wallpaper/model/image_base.dart';
import 'package:wallpaper/model/options_base.dart';

class MoeList extends StatefulWidget {
  final String sort;
  const MoeList({super.key, required this.sort});

  @override
  State<MoeList> createState() => _MoeListState();
}

class _MoeListState extends State<MoeList> with AutomaticKeepAliveClientMixin {
  List<ImageBase> imgs = [];
  Set<String> results = <String>{};
  ScrollController scrollController = ScrollController();
  bool isLoading = false;

  void getData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await getMoeImgs(sort: widget.sort);
      List pics = res.data['pic'];
      for (var i = 0; i < pics.length; i++) {
        String large = pics[i].toString().replaceAll('?thumbnail=large', '');
        if (results.contains(large)) continue;
        results.add(large);
        ImageBase img = ImageBase(
          smallPath: pics[i],
          largePath: large,
          tags: '',
        );
        imgs.add(img);
      }
    } catch (e) {
      BotToast.showText(text: '加载失败');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    scrollController.addListener(() {
      if (isLoading) return;
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getData();
      }
    });
    super.initState();
    getData();
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return RefreshIndicator(
      onRefresh: () {
        setState(() {
          imgs.clear();
          results.clear();
        });
        getData();
        return Future.delayed(
            Duration(milliseconds: OptionsBase().refreshTime));
      },
      child: imgs.isEmpty && !isLoading
          ? SingleChildScrollView(
              physics: AlwaysScrollableScrollPhysics(),
              child: Empty(),
            )
          : CustomScrollView(
              controller: scrollController,
              slivers: [
                SliverGrid(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: OptionsBase().imageColumns(context),
                    childAspectRatio: widget.sort == 'pc' ? 1.5 : 0.7,
                  ),
                  delegate: SliverChildBuilderDelegate(
                    (context, index) => buildItem(context, index),
                    childCount: imgs.length,
                  ),
                ),
                if (isLoading)
                  SliverToBoxAdapter(
                    child: Center(
                      child: Padding(
                        padding: EdgeInsets.only(
                            top: MediaQuery.of(context).size.height * 0.4),
                        child: CircularProgressIndicator(),
                      ),
                    ),
                  ),
              ],
            ),
    );
  }

  Widget buildItem(context, int index) {
    return Container(
      margin: EdgeInsets.all(OptionsBase().padding / 2),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Theme.of(context).colorScheme.shadow,
              offset: Offset(1, 2),
              blurRadius: 2,
            ),
          ]),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: GestureDetector(
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => ImageView(
                          images: imgs,
                          selectedIndex: index,
                          resetGetdata: () {},
                        )));
          },
          child: Stack(alignment: Alignment.bottomLeft, children: [
            SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: ImageLoad(imageUrl: imgs[index].smallPath)),
            Container(
                color: const Color.fromARGB(24, 158, 158, 158),
                width: double.infinity,
                height: imgs[index].tags == "" ? 0 : 20,
                child: Padding(
                  padding: const EdgeInsets.only(left: 5, right: 5),
                  child: Text(
                    imgs[index].tags,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    style: TextStyle(color: Colors.white, fontSize: 13),
                  ),
                )),
          ]),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
